<?php
namespace Home\Controller;
use Think\Controller;
use Home\Service\ClockTimeService;
use Home\Service\AccountService;
// +----------------------------------------------------------------------
// | Date:2017年3月14日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class CronController extends Controller{
    
    protected $cur_day;
    protected $pve_day;
    protected $appurl = '';
    protected $debug=0;
    protected $debug_wx_openid = '';
    public function _initialize(){
        $this->appurl = C('HOST_NAME').'/'.basename(dirname(dirname(dirname(dirname(__FILE__))))).'/index.php?g=Home';
        $this->cur_day = date('Y-m-d');
        $this->pve_day = date('Y-m-d',strtotime($this->cur_day)-86400);
        $this->debug=I('debug') ? I('debug') : 0;
        
    }
    
    
    /**
     * 计划任务：每天8点执行,1提交加班申请，2发送微信消息告知领导
     * 1.抓取attendanceDay表，获取attUser
     *   
     *  2.获取全部员工数据；
     *  
     *  循环全部员工数据,比较date值和date_off,
     *      date < date_off 提交申请，获取leaderInfo,发送微信
     *      如果获取不到att数据,就是旷工
     *      
     *      只是提交加班申请，并没有执行审核方法，审核只是简单修改状态而已
     * @param unknown $userInfo
     * date:2017年3月14日
     * author: EK_熊
     */
    public function morning_overtime($sendWechat=true){
        $sendWechatStr = $sendWechat ? '是' :'否';
        echo "微信发送:{$sendWechatStr}<br/>";
        
        $appModel = D('Apply');
        $attDayModel = D('AttendanceDay');
        $attModel = M('Attendance');
        
        $cur_day = $this->cur_day;
        $pve_day = $this->pve_day;
        
        
        $accountService = new AccountService();
        //只获取需要计算考勤的员工
        $allEmployee = $accountService->get_all_user_baseinfo('sn,wx_openid,ep_name as name,leader_id,dep_id,dep_name,ep_id as id,privilege',['is_attendance'=>1,'status'=>1,'sn'=>['neq','']]);//全部员工
        foreach ($allEmployee as $k=>$v ){
            $map['date'] = $pve_day;
            $map['sn'] = $k;
            $attendance = $attDayModel->where($map)->find();
            //找不到该员工的考勤数据，表示【旷工】
            if (empty($attendance)) {
                //【发送旷工提醒】,发送的前提：1.前一天是工作日，2微信openid必须存在
                if (is_work_day($pve_day) && $v['wx_openid']) {
                    if ($sendWechat) {
                        //发送旷工消息
                        $this->_message_absenteeism($v, $pve_day);
                    }
                    $absentBox[] = $v['name'];
                }
            }else{
                //找到了员工数据，对比date和duty_off，检查是否跨天下班
                $date_duty_off = date('Y-m-d',strtotime($attendance['duty_off']));
                if ($attendance['date'] < $date_duty_off) {
                                    
                    //召唤他的领导，提交申请
                    $post['start_time'] = "$pve_day 20:00:00";//申请记录的加班开始时间，默认设置定0:00:00
                    $post['end_time'] = $attendance['duty_off'];//最新的打卡时间点
                    $post['type'] = 5;//申请类型，系统提交的加班申请
                    $post['content'] = '凌晨加班！';//申请类型，系统提交的加班申请
                    
                    $clockTimeService = new ClockTimeService($post['start_time'],$attendance['duty_off']);
                    $vacation = $clockTimeService->get_intrval_work_time();
                    $leaderInfo = $accountService->get_leader_info('ep_id',$v['id'], 'wx_openid,ep_name as name,sn');

                    /* 加班申请的核心代码 */
                    $submitApply = $appModel->apply_submit($v,$vacation,$post);
                    //发送微信消息，通知主管(拥有中心负责人考勤权的不需要发送)
                    $privilege = explode(',',$v['privilege']);
                    if ($leaderInfo['wx_openid'] && !in_array(1,$privilege)) {
                        if ($sendWechat) {
                           $overtimeInfo = [
                               'date'=>$cur_day,
                               'name'=>$v['name'],
                               'start_time'=>$post['start_time'],
                               'end_time'=>$post['end_time'],
                           ];
                           $this->_message_overtime($leaderInfo,$overtimeInfo,$vacation['total_min']);
                        }
                        $leaderBox[$leaderInfo['name']][] = $v['name'];
                    }
                    
                }
                
            }
            
        }
        
        if (!$sendWechat) {
            dump('旷工同事：');
            dump($absentBox);
            dump('以下领导会收到加班申请：');
            dump($leaderBox);
        }
    }
    
    
    /**
     * 审批通宵加班的数据
     * 批量通过，简单设置状态值为1
     * 
     * date:2017年4月28日
     * author: EK_熊
     */
    public function morning_overtime_pass(){
        
        $appModel = M('Apply');
        $map["DATE_FORMAT(`start_time`,'%Y-%m-%d')"]=['ELT',$this->pve_day];
        $map['status'] = 0;
        $map['type'] = 5;
        $ret = $appModel->where($map)->setField('status',1);
    }
    
    /**
     * 检查微信消息是否已经发送，避免重复发送
     * @param unknown $sn
     * @param unknown $type
     * date:2017年4月25日
     * author: EK_熊
     */
    private function _check_message_send($sn,$type){
        $map['to_sn']=$sn;
        $map['type']=$type;
        $map['date']=date('Y-m-d');
        $ret = M('MessageWechat')->where($map)->find();
        return $ret;
    }
    
    /**
     * 检查当天日期是否处在，微信接收目标用户的请假期内
     * @param unknown $sn
     * date:2017年4月27日
     * author: EK_熊
     */
    private function _check_leave($sn='',$date=''){
        $nextDay=date('Y-m-d',strtotime($date)+86400);
        $appModel = M('Apply');
        $map['sn']=$sn;
        $map["DATE_FORMAT(`start_time`,'%Y-%m-%d')"]=['ELT',$date];
        $map["DATE_FORMAT(`end_time`,'%Y-%m-%d')"]=['EGT',$date];
        $map["status"]=1;
        $ret = $appModel->where($map)->find();
        
        if ($ret['type'] == 3 || $ret['type'] == 5){
            //加班类型，要检查打卡点，区分其他的假期
            $mapAtt['sn']=$sn;
            $mapAtt['recept_time']=['EGT',"$nextDay 06:00:00"];
            $att = M('Attendance')->where($mapAtt)->find();
            if (!$att) return false;
        }
        
        return $ret;   
    }
    
    /**
     * 发送微信消息，加班通知
     * @param unknown $leaderInfo
     * @param unknown $overtimeInfo
     * @param unknown $totalMin
     * date:2017年4月24日
     * author: EK_熊
     */
    private function _message_overtime($leaderInfo,$overtimeInfo,$totalMin){
        $mesagType = 6;
        $check = $this->_check_message_send($leaderInfo['sn'], $mesagType);
        if ($check) return false;
        
        $time_str = time_hour_min_zh($totalMin);
        //发送微信消息
        $data=[
            "first"=>[
                'value'=>'',
                "color"=>"#173177"
            ],
            "keyword1"=>[
                "value"=>"{$overtimeInfo['name']}",
                "color"=>"#173177"
            ],
            "keyword2"=>[
                "value"=>"{$overtimeInfo['start_time']}",
                "color"=>"#173177"
            ],
            "keyword3"=>[
                "value"=>"{$overtimeInfo['end_time']}",
                "color"=>"#173177"
            ],
            "keyword4"=>[
                "value"=>"{$time_str}",
                "color"=>"#173177"
            ],
            "keyword5"=>[
                "value"=>'系统自动发送',
                "color"=>"#173177"
            ],
            "remark"=>[
                "value"=>'点击进入考勤系统',
                "color"=>"#173177"
            ]
        ];
        
        $wxInfo =[
            'wx_open_id'=>$leaderInfo['wx_openid'],
            'wx_data'=>$data,
            'wx_tpl_id'=>'94iZttQ2ynTy4MLM6vi5FAefzOGL4jMrnVKLxRdcQZ8',
            'url'=>$this->appurl."&m=Approver&a=index",
        ] ;
        $logInfo = [
            'from_sn'=>C('SYS_SN'),
            'from_name'=>C('SYS_NAME'),
            'to_sn'=>$leaderInfo['sn'],
            'to_name'=>$leaderInfo['name'],
            'type'=>$mesagType,
            'info'=>"[{$overtimeInfo['name']}][{$overtimeInfo['date']}]凌晨加班！！",
        ];
        $sendwechat = wechat_send_template_msg($wxInfo,$logInfo);

    }
    
    
    
    /**
     * 发送旷工微信消息
     * @param unknown $userInfo   姓名，日期，openid,
     * @param string $sendwechat
     * date:2017年4月21日
     * author: EK_熊
     */
    private function _message_absenteeism($userInfo,$date){
        //检查是否已经提交了请假
        $check_leave = $this->_check_leave($userInfo['sn'],$date);
        if ($check_leave) return false;

        //检查是否已经发送微信    
        $check = $this->_check_message_send($userInfo['sn'], 2);
        if ($check) return false;
        
        
        $wx_openid = $userInfo['wx_openid'];
        $name = $userInfo['name'];
        
        if (!$wx_openid || !$userInfo) return false;
        $jumpurl = $this->appurl."&m=Index&a=index";
        $wx_tpl_id = 'flOuFJS8vEcJLMTGOKNzLpDPFAyBPQDtiSjN_8JyZIg';
        $type = 2;
        $str_employee = ["{$name},您好！","{$date}","旷工",'点击查看详情'];
        $log_remark = "[{$name}][{$date}]旷工！！";
        //给员工本人发送微信消息
        wx_send_msg_sys($userInfo['wx_openid'], $userInfo['name'], $userInfo['sn'], $str_employee, $wx_tpl_id, $type, $log_remark,$jumpurl,$this->debug);
        
        //给行政管理员发送微信消息
//         $config = D('Options')->getOption('att_base');
//         $log_remark = "[{$userInfo['dep_name']}]{$userInfo['name']}旷工！！";
//         $str_admin = ["您收到一条员工旷工提醒","{$date}",$log_remark,'点击查看详情'];
//         wx_send_msg_sys($config['admin_wx_openid'], $config['admin_name'], $config['admin_sn'], $str_admin, $wx_tpl_id, $type, $log_remark,$jumpurl,$this->debug_wx_openid);
        
        return true;
    }
    
    /**
     * 每月执行一次的，缺勤数和可补休时间的一次抵消，计算获取可抵消的时间，并发消息通知用户
     * 具体流程：1.系统自动提交一条审核通过的‘补休申请’；实现抵消效果（因为月结的缺勤数=本月1号至昨天的应出勤分钟数- 入职/离职时间- 期间全部假期时间 -本月1号至昨天的实际出勤数）
     *        2.微信通知员工自己，
     *        
     * 新修改：每月提醒员工，剩余可补休时间是多少        
     * @param string $execDate
     * date:2017年4月19日
     * author: EK_熊
     */
    public function offset_absent_mon($sendwechat = true){
        $attDayModel = D('AttendanceDay');
        $account = new AccountService();
        $execDate = date('Y-m-d');
             
         $allUser= $account->get_all_user_baseinfo('sn,wx_openid,ep_name',['wx_openid'=>['exp','is not null'],'status'=>1]);
        
        //获取全部员工的sn
         $snBoxAll = array_keys($allUser);
        //根据执行的日期，获取上一个月的起止日期，60天前的日期
        $preMon = date('Y-m',strtotime("$execDate -1 month"));//上一个月的年月
        $preMon_ch = date('Y年m月',strtotime("$execDate -1 month"));
        $preMon_s = $preMon.'-01';//上一个的开始
        $preMon_e = date('Y-m-d',strtotime("$preMon_s +1 month -1 day"));//上一个月的最后一天
        $lastDay = date('Y-m-d',strtotime("$execDate -1 day"));//昨天
        $preDay60 = date('Y-m-d',strtotime("$execDate -61 day"));//昨天,往前推60天
        
        //遍历员工的可补休时间
        foreach ($snBoxAll as $sn){
            $remain_overtime = $attDayModel->count_remain_overtime($sn,$preDay60,$preMon_e);
            if ($remain_overtime > 480) {
                $userinfo = $allUser[$sn];
                $this->_message_compensatory($userinfo, $remain_overtime,$preMon_ch,$sendwechat);//发送微信模板消息
            }
        }
        
    }
    
    
    /**
     * 发送微信模板消息
     * @param unknown $userInfo
     * @param unknown $absent
     * @param unknown $preMon_ch
     * @param unknown $sendwechat
     * @return boolean
     * date:2017年5月8日
     * author: EK_熊
     */
    private function _message_compensatory($userInfo, $absent,$preMon_ch,$sendwechat){
        $check = $this->_check_message_send($userInfo['sn'], 3);
        if ($check) return false;
        //发送微信模板消息
        if ($sendwechat){
            $url = C('HOST_NAME').U('Index/index');
            $data=[
                "first"=>[
                    'value'=>"您好，您有一条考勤消息提醒",
                    "color"=>"#173177"
                    ],
                "keyword1"=>[
                    "value"=>"{$userInfo['ep_name']}",
                    "color"=>"#173177"
                        ],
                "keyword2"=>[
                    "value"=>CURRENT_TIME,
                    "color"=>"#173177"
                ],
                "keyword3"=>[
                    "value"=>"$preMon_ch,您有{$absent}分钟的可补休时间,赶紧去调休吧~",
                    "color"=>"#173177"
                ],
                "remark"=>[
                    "value"=>'点击查看详情',
                    "color"=>"#173177"
                ]
                ];
            $wxInfo =[
                'wx_open_id'=>$userInfo['wx_openid'],
                'wx_data'=>$data,
                'wx_tpl_id'=>'afc56uBOBdeQVlK5CpOi0pkDFWrBCuIIwIvNmCFSFfg',
                'url'=>$this->appurl."&m=index&a=index",
            ] ;
            $logInfo = [
                'from_sn'=>C('SYS_SN'),
                'from_name'=>C('SYS_NAME'),
                'to_name'=>$userInfo['ep_name'],
                'to_sn'=>$userInfo['sn'],
                'type'=>3,
                'info'=>"{$absent}分钟的可补休时间用于抵消缺勤数",
                ];
            $sendwechat = wechat_send_template_msg($wxInfo,$logInfo);
        }
    }
    
    /**
     * 每天执行，检查是否满足一年，五年，十年
     * 
     * date:2017年5月26日
     * author: EK_熊
     */
    public function update_annual_daily($day=''){

        //获取目前在职的全部员工
        $account = new AccountService();
        $userInfo_map = [
            'status'=>1,
        ];
        $userInfo = $account->get_all_user_baseinfo('sn,join_date',$userInfo_map);
        $i = 0;
        if ($userInfo) {
            foreach ($userInfo as $k=>$v){
                $ret = D('AnnualLeave')->update_daily($k,$v,$day);
                if ($ret) $i++;
            }
        }
        echo '执行完毕,成功执行了'.$i."条记录";
    }
    
    /**
     * 自动重置(重新创建)员工年假，每年一月一号执行
     *
     * date:2017年5月26日
     * author: EK_熊
     */    
    public function update_annual_yearly(){
        //获取目前在职的全部员工
        $account = new AccountService();
        $userInfo_map = [
            'status'=>1,
        ];
        $userInfo = $account->get_all_user_baseinfo('sn,join_date',$userInfo_map);
        $i = 0;
        if ($userInfo) {
            foreach ($userInfo as $k=>$v){
                $ret = D('AnnualLeave')->update_yearly($k,$v);
                if ($ret) $i++;
            }
        }
        echo '执行完毕,成功执行了'.$i."条记录";        
    }
    
    /**
     * 每年的3月1日进行，消除
     * 
     * date:2018年1月3日
     * author: EK_熊
     */
    public function annual_adjust_clear(){
        $year = date('Y', strtotime(CURRENT_TIME));
        $year_start = $year."-01-01";
        $year_end = $year."-12-31";
        $map['adjust'] = ['neq',0];
        $map['start_date'] = ['egt',$year_start];
        $map['end_date'] = ['elt',$year_end];
        $annualModel = M('AnnualLeave');
        
        $data = $annualModel->where($map)->field('id,sn,adjust,adjust_consume')->select();
        if ($data) {
            //更新前的数据保存
            $filenameTime = date('Ymd_H_i_s');
            $data_str = json_encode($data);
            $filename="./annual_adjust_{$filenameTime}.txt";
            $handle=fopen($filename,"w");
            $str=fwrite($handle,$data_str);
            fclose($handle); 
        }
       $anModel = M('AnnualLeave')->where($map)->setField('adjust',0); 
    }
    
    
    
    
    /**
     * 每周五 发送微信消息通知主管处理未审批的申请
     * 
     * date:2017年5月27日
     * author: EK_熊
     */
    public function alert_leader_approval(){
        $where['status'] = 0;
        $underling_sn_box = M('Apply')->where($where)->getField('sn',true);
        $account = new AccountService();
        $lead_box = $account->get_leader_info_all(['sn'=>['in',$underling_sn_box]],'sn,wx_openid,ep_name');
        
        //发送微信消息
        foreach ($lead_box as $k=>$v){
            $str=['您好,温馨提醒','审批提醒',$v['ep_name'],'本周您还有未处理的申请，请及时审批哦。',date('Y-m-d H:i:s'),'点击进入系统'];
            wx_send_msg_sys($v['wx_openid'], $v['ep_name'], $v['sn'], $str, 'SbHAMhpjYsh2Cqt1wwR9RG6VO1fzrw7899B3qfh5rl0', 5, '未处理审核提醒');
        }
        
    }
    
    

}